package com.shortchainsystem.model.base;

import com.shortchainsystem.model.exception.CustomCodeEnum;
import lombok.Data;
import lombok.ToString;

import java.io.Serializable;

/**
 *   TODO 通用返回结果，服务端响应的数据都会封装成此对象
 */
@Data
@ToString
public class Result<T> implements Serializable{
    private Integer code;                    //编码（1成功，其他失败）
    private String message;                      //错误信息
    private T data;                          //数据

    public Result() {
        this.code = 200;
    }

    public Result(Integer code, T data) {
        this.code = code;
        this.data = data;
    }

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.message = msg;
        this.data = data;
    }

    public Result(CustomCodeEnum codeEnum, T data) {
        this.code = codeEnum.getCode();
        this.message = codeEnum.getErrorMessage();
        this.data = data;
    }

    public Result(Integer code, String msg) {
        this.code = code;
        this.message = msg;
    }

    public static Result errorResult(int code, String msg) {
        Result result = new Result();
        return result.error(code, msg);
    }

    public static Result okResult(int code, String msg) {
        Result result = new Result();
        return result.ok(code, null, msg);
    }

    public static Result okResult(Object data) {
        Result result = setAppHttpCodeEnum(CustomCodeEnum.SUCCESS, CustomCodeEnum.SUCCESS.getErrorMessage());
        if(data!=null) {
            result.setData(data);
        }
        return result;
    }

    public static Result errorResult(CustomCodeEnum enums){
        return setAppHttpCodeEnum(enums,enums.getErrorMessage());
    }

    public static Result errorResult(CustomCodeEnum enums, String errorMessage){
        return setAppHttpCodeEnum(enums,errorMessage);
    }

    public static Result setAppHttpCodeEnum(CustomCodeEnum enums){
        return okResult(enums.getCode(),enums.getErrorMessage());
    }

    private static Result setAppHttpCodeEnum(CustomCodeEnum enums, String errorMessage){
        return okResult(enums.getCode(),errorMessage);
    }

    public Result<?> error(Integer code, String msg) {
        this.code = code;
        this.message = msg;
        return this;
    }

    public Result<?> ok(Integer code, T data) {
        this.code = code;
        this.data = data;
        return this;
    }

    public Result<?> ok(Integer code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.message = msg;
        return this;
    }

    public Result<?> ok(T data) {
        this.data = data;
        return this;
    }
}
